<template>
    <el-form @submit.native.prevent ref="formRule" :model="form" :rules="rules">
        <div>
            <el-button @click="onClickPushApi" style="width: 100%;" type="primary" plain>+1 path</el-button>
        </div>
        <el-table :data="form.apis" border style="width: 100%;margin-top: 10px;">
            <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
            <el-table-column v-if="!isMobile" type="index"> </el-table-column>
            <el-table-column prop="path" label="path">
                <template v-slot="{row}">
                    <el-form :model="row" :ref="`path${row.key}`" :key="row.key">
                        <el-form-item
                            prop="apiId"
                            :rules="{
                                required: true,
                                message: 'path不能为空',
                                trigger: ['blur', 'change']
                            }"
                            style="margin-bottom: 14px;"
                        >
                            <el-select
                                v-model="row.apiId"
                                filterable
                                clearable
                                placeholder="请输入关键字检索"
                                style="width: 100%;"
                                @change="onChangeRow(row)"
                            >
                                <el-option
                                    v-for="item in optionsApis"
                                    :key="item._id"
                                    :label="`${item.path} ${item.methods.join(',')} ${item.remark || ''}`"
                                    :value="item._id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column prop="methods" label="methods">
                <template v-slot="{row}">
                    <el-form :model="row" :ref="`methods${row.key}`" :key="row.key">
                        <el-form-item
                            prop="methods"
                            :rules="{
                                required: true,
                                message: 'methods不能为空',
                                trigger: ['blur', 'change']
                            }"
                            style="margin-bottom: 14px;"
                        >
                            <el-checkbox-group v-model="row.methods">
                                <el-checkbox v-for="item in row.methodsTypes" :key="item" :label="item" name="type">{{
                                    item
                                }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column prop="operactor" label="" :width="80">
                <template v-slot="{row, $index}">
                    <el-button @click="onClickClose(row, $index)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-form>
</template>
<script>
import {mapState} from 'vuex';
import {METHODS_TYPE} from '@/views/system/interface/constants';
export default {
    name: 'FormTable',
    props: {
        options: {
            type: Array,
            required: true,
            default: () => []
        },
        value: {
            type: Array,
            required: true,
            default: () => []
        }
    },
    data() {
        return {
            methodsTypes: [],
            METHODS_TYPE,
            form: {path: '', apis: []},
            rules: {}
        };
    },
    computed: {
        ...mapState('app', {
            isMobile: state => state.isMobile
        }),
        optionsApis() {
            return this.options;
        }
    },
    watch: {
        value: {
            handler(val = []) {
                val.forEach(item => this.onChangeRow(item));
                this.form = {apis: [...val]};
            },
            immediate: true
        }
    },
    methods: {
        onChangeRow(row) {
            if (row.apiId) {
                if (typeof row.apiId === 'object') {
                    row.methodsTypes = row.apiId.methods;
                } else {
                    const target = this.options.find(item => item._id === row.apiId);
                    row.methodsTypes = target ? target.methods : [];
                }
                if (Array.isArray(row.methods) && row.methods.length === 0 && row.methodsTypes.length > 0) {
                    row.methods = [...row.methodsTypes];
                }
            } else {
                row.methodsTypes = [];
            }
        },
        // 表单校验
        async validator() {
            return new Promise(async (resolve, reject) => {
                const errors = [];
                for (const item of this.form.apis) {
                    for (const keyStr of ['path', 'methods']) {
                        await new Promise(resolve => {
                            const target = this.$refs[`${keyStr}${item.key}`];
                            if (target) {
                                target.validate((valid, fields) => {
                                    if (!valid) {
                                        errors.push({item, keyStr, fields});
                                    }
                                    resolve();
                                });
                            } else {
                                console.warn('validator', this.$refs[`${keyStr}${item.key}`]);
                            }
                        });
                    }
                }

                return errors.length === 0 ? resolve() : reject(errors);
            });
        },
        onClickClose(api, index) {
            const apis = [...this.form.apis];

            apis.splice(index, 1);

            this.form = {...this.form, apis};
            this.$emit('input', apis);
            this.$emit('change', apis);
        },
        onClickPushApi() {
            const apis = [
                {
                    path: '',
                    methods: [],
                    // methods: ['get', 'post', 'delete', 'put'],
                    key: Math.random().toString()
                },
                ...this.form.apis
            ];
            this.form = {...this.form, apis};
            this.$emit('input', apis);
            this.$emit('change', apis);
        }
    }
};
</script>
